import {Component, EventEmitter, Input, Output} from '@angular/core';
import {ActionSheetController, IonicPage, NavController, NavParams} from 'ionic-angular';
import {ImagePicker, ImagePickerOptions} from "@ionic-native/image-picker";
import {Camera, CameraOptions} from '@ionic-native/camera';
import {AppConfig} from "../../../app/appConfig";
import {HttpClient} from "@angular/common/http";
import {AppUrl, TIME_OUT} from "../../../app/app.general";
import {CommonService} from "../../../app/common.service";

/**
 * 图片上传公共组件 调用手机原生：手机拍照 和 相册选择
 * 输入：
 *    [type]：图片类型,整型
 *    [upload]:上传标志，boolean型，为true表示图片已选择完成，不可再次选择，马上开始上传
 *    [old]:老图片id，string型，为了方便更改图片，请将老图片的id传入
 *
 * 输出：
 *    (imgId):上传图片存储与数据库中的id,string型
 *    (success):上传结果，boolean型，为true表示是\上传成功
 */

@IonicPage()
@Component({
  selector: 'page-upload-file',
  templateUrl: 'upload-file.html',
})
export class UploadFilePage {
  private imgType: any;
  private iId: any;

  @Input()
  set type(type: any) {
    this.imgType = type;
  }

  @Input()
  set upload(upload: boolean) {
    if (upload) {
      this.confirmChoose();
    }
  }

  @Input()//为了方便更改图片，请将老图片的id传入
  set old(oldImgId) {
    if (oldImgId) {
      this.oldImgId = oldImgId;
      this.getImg = true;
      this.getSrc = true;
      this.imgSrc = AppUrl.image.getById + this.oldImgId;
    }
  }

  @Output()
  imgId = new EventEmitter<any>();//输出新图片的数据库中的id

  @Output()
  success = new EventEmitter<boolean>();//输出true表示上传成功

  private imgSrc;        //缩略图图片流
  private getImg = false;//标记是否已经选择或拍摄了一张照片
  private getSrc = false;//标记是否传入了图片源
  private oldImgId;
  private changeOld = false;//标记是否修改了图片源

  constructor(public navCtrl: NavController,
              public navParams: NavParams,
              private imagePicker: ImagePicker,
              private camera: Camera,
              private appConfig: AppConfig,
              private httpService: HttpClient,
              private cs: CommonService,
              private actionSheetCtrl: ActionSheetController,) {
  }

  presentActionSheet() {
    let buttons = [];
    buttons.push({
      text: '相册选择',
      handler: () => {
        this.choose();
      }
    });
    buttons.push({
      text: '拍照上传',
      handler: () => {
        this.take();
      }
    });
    let actionSheet = this.actionSheetCtrl.create({
      buttons: buttons
    });
    actionSheet.present();
  }

  choose() {//调用相册原生
    this.imagePicker.hasReadPermission().then(data => {
      if (data) {
        let options: ImagePickerOptions = {
          maximumImagesCount: 1,
          width: 400,
          height: 400,
          quality: 30,
          outputType: 1
        };
        this.imagePicker.getPictures(options).then((results) => {
          // for (let i = 0; i < results.length; i++) {//多张图片时循环处理
          //
          // }
          this.imgSrc = results[0];
          this.getImg = true;
          this.getSrc = false;
          this.changeOld = true;
        }, (err) => {
          this.appConfig.presentToast(err);
        });
      }
      else {
        this.appConfig.presentToast("权限不足，请到设置中开启文件读写权限")
      }
    });
  }

  take() {//调用相机原生
    const options: CameraOptions = {
      quality: 30,
      destinationType: this.camera.DestinationType.DATA_URL,
      encodingType: this.camera.EncodingType.JPEG,
      mediaType: this.camera.MediaType.PICTURE,
      saveToPhotoAlbum: true,
      sourceType: this.camera.PictureSourceType.CAMERA,//拍照时，此参数必须有，否则拍照之后报错，照片不能保存
      correctOrientation: true  //Corrects Android orientation quirks
    };
    this.camera.getPicture(options).then((imageData) => {
      this.imgSrc = imageData;
      this.getImg = true;
      this.getSrc = false;
      this.changeOld = true;
    }, (err) => {
      this.appConfig.presentToast(err);
    });
  }

  confirmChoose() {
    if (this.changeOld) {
      this.appConfig.presentLoading("正在上传");
      let postUrl = '';
      if (this.imgType == 0) {
        postUrl = AppUrl.image.uploadU;
      }
      else if (this.imgType == 1) {
        postUrl = AppUrl.image.uploadF;
      }
      else if (this.imgType == 2) {
        postUrl = AppUrl.image.uploadR;
      }
      else {
        this.appConfig.presentToast('无法识别的图片类型');
      }
      this.httpService.post(postUrl, {imgSrc: this.imgSrc, oldImgId: this.oldImgId}).subscribe(data => {
        this.appConfig.loader.dismiss();
        let temp: any = data;
        if (temp.code == 200) {
          this.iId = temp.data;
          this.success.emit(true);
          this.imgId.emit(this.iId);
        }
        else {
          this.success.emit(false);
          this.appConfig.presentToast(temp.msg);
        }

      }, e => {
        this.appConfig.loader.dismiss();
        this.success.emit(false);
        this.cs.httpError(e);
      })
    }
    else {
      this.imgId.emit(this.oldImgId);
    }
  }

  removeImage() {
    this.imgSrc = '';
    this.getImg = false;
  }
}
